package com.bawei.property;

import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.common.RouterPath;
import com.bawei.common.mvi.BaseMviActivity;
import com.bawei.image.engine.GlideEngine
import com.bawei.property.adapter.CarColorAdapter
import com.bawei.property.adapter.CarImageAdapter
import com.bawei.property.databinding.ActivityParkSelectBinding;
import com.bawei.property.entity.CarApplyValues
import com.bawei.property.entity.CarColorValues
import com.bawei.property.entity.CarImageEntity
import com.bawei.property.intent.ParkSelectViewIntent
import com.bawei.property.uistate.ParkSelectUiState
import com.bawei.property.viewmodel.ParkSelectViewModel
import com.blankj.utilcode.util.GsonUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import dagger.hilt.android.AndroidEntryPoint;
import kotlinx.coroutines.launch
import java.sql.Date
import java.text.SimpleDateFormat
import java.util.ArrayList

/**
 * 车位选择页面
 */

@Route(path = RouterPath.PATH_PARK_SELECT)
@AndroidEntryPoint
class ParkSelectActivity: BaseMviActivity<ActivityParkSelectBinding>() {

    private val mViewModel: ParkSelectViewModel by viewModels()

    @Autowired
    lateinit var carApplyEntity: CarApplyValues

    private lateinit var mColorAdapter: CarColorAdapter
    private lateinit var mImageAdapter: CarImageAdapter

    override fun getLayoutId(): Int = R.layout.activity_park_select

    override fun initViews() {
        ARouter.getInstance().inject(this)

        mDataBinding.includePageTitle.ivBack.setOnClickListener {
            this@ParkSelectActivity.finish()
        }
        mDataBinding.includePageTitle.tvTitle.text = "车位选择"

        //模拟数据
        var startDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(carApplyEntity.parkStart.toLong() * 1000L)).toString()
        var endDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(carApplyEntity.parkEnd.toLong() * 1000L)).toString()
        mDataBinding.tvUseDate.text = "$startDate - $endDate"
        mDataBinding.tvApplyName.text = carApplyEntity.parkName
        mDataBinding.tvApplyDate.text = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(carApplyEntity.parkTime.toLong() * 1000L)).toString()

        //初始化车辆颜色列表
        mDataBinding.rvCarColors.layoutManager = LinearLayoutManager(this@ParkSelectActivity, LinearLayoutManager.HORIZONTAL, false)
        mColorAdapter = CarColorAdapter(R.layout.item_car_color)
        mDataBinding.rvCarColors.adapter = mColorAdapter
        //车辆图片列表
        mDataBinding.rvCarImgs.layoutManager =  LinearLayoutManager(this@ParkSelectActivity, LinearLayoutManager.HORIZONTAL, false)
        mImageAdapter = CarImageAdapter(R.layout.item_car_image)
        mDataBinding.rvCarImgs.adapter = mImageAdapter

        //添加车辆图片
        mDataBinding.ivAddCarImg.setOnClickListener {
            PictureSelector.create(this@ParkSelectActivity).openGallery(SelectMimeType.ofImage()).setImageEngine(GlideEngine.createGlideEngine()).forResult(object : OnResultCallbackListener<LocalMedia>{
                override fun onResult(result: ArrayList<LocalMedia>) {
                    var list = mutableListOf<CarImageEntity>()
                    result.forEach {
                        list.add(CarImageEntity(it.availablePath, it.availablePath.substring(it.availablePath.lastIndexOf("/"))))
                    }
                    mImageAdapter.data.addAll(list)
                    mImageAdapter.notifyDataSetChanged()

                    uploadImages(list as List<CarImageEntity>)
                }

                override fun onCancel() {

                }

            })
        }


        //提交车辆信息
        mDataBinding.tvSubmit.setOnClickListener {
            submitParkApplyInfo()
        }
    }


    private fun submitParkApplyInfo(){
        lifecycleScope.launch {
            mViewModel.channel.send(ParkSelectViewIntent.SubmitParkApply({}))
        }
    }

    //上传图片
    private fun uploadImages(list: List<CarImageEntity>){
        lifecycleScope.launch {
            mViewModel.channel.send(ParkSelectViewIntent.UploadCarImage(list))
        }
    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(ParkSelectViewIntent.LoadCarColors)
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is ParkSelectUiState.LoadCarColorsSuccess -> {
                    mColorAdapter.data.addAll(it.data as MutableList<CarColorValues>)
                    mColorAdapter.notifyDataSetChanged()

                }
                is ParkSelectUiState.UploadImageSuccess -> {
                    showMessage("上传成功")
                    Log.i("=======", "上传成功返回的图片地址: ${GsonUtils.toJson(it.pathUrls)}")
                }
                is ParkSelectUiState.SubmitParkApplySuccess -> {
                    showMessage(it.msg)
                    this@ParkSelectActivity.finish()
                }
                is ParkSelectUiState.LoadCarColorsFail -> showMessage(it.msg)
                is ParkSelectUiState.LoadCarColorsFail -> showMessage(it.msg)
                is ParkSelectUiState.SubmitParkApplyFail -> showMessage(it.msg)
                else -> {}
            }
        }
    }



}